import path from 'path'
import alias from '@rollup/plugin-alias'
import commonjs from '@rollup/plugin-commonjs'
import { nodeResolve } from '@rollup/plugin-node-resolve'
import { getBabelOutputPlugin } from '@rollup/plugin-babel'
import typescript from '@rollup/plugin-typescript'
import json from '@rollup/plugin-json'
import clear from 'rollup-plugin-clear'
import { terser } from 'rollup-plugin-terser'

const isProd = !process.env.ROLLUP_WATCH

const config = {
  input: 'src/main.ts',
  output: { dir: 'dist', format: 'cjs' },
  plugins: [
    alias({
      entries: [{ find: '@/', replacement: path.resolve(__dirname, './src/') }],
    }),
    clear({ targets: ['./dist'] }),
    typescript(),

    // 只识别 src 中的文件依赖, 忽略 node_modules 的(部署时,会安装依赖)
    nodeResolve({ preferBuiltins: true, moduleDirectories: ['./src'] }),

    // babel 处理
    // 需要额外安装:
    // 1.@babel/preset-env
    // 2.@babel/plugin-transform-runtime
    // 3.@babel/core
    getBabelOutputPlugin({
      presets: ['@babel/preset-env'],
      plugins: ['@babel/plugin-transform-runtime'],
    }),
    commonjs(),
    json(),
    isProd && terser(),
  ],
}

export default config
